# encoding: utf-8
# @author: wangxin
# @software: garner
# @file: detailViews.py
# @time: 2025/2/20 19:37

from lib2to3.fixes.fix_input import context

from django.shortcuts import render, redirect
from django.template.defaulttags import comment
from django.urls import reverse
from django.views import View
from unicodedata import category

from home.models import Article, Articlecategory, Comment
from user.apps import UserConfig
from user.models import User


class detailView(View):
    def get(self, request):
        id = request.GET.get('id')
        categoies=Articlecategory.objects.all()
        article=Article.objects.get(id=id)
        # 热点文章推荐
        hot_articles = Article.objects.order_by('-total_views')[:3]
        context = {
            'article': article,
            'categoies': categoies,
            'category': article.category,
            'hot_articles': hot_articles,
        }

       #浏览量加1
        article.total_views += 1
        article.save()

        return render(request, 'detail.html',context=context)
    def post(self,request):
        user = request.user
        if user.is_authenticated:
            id=request.POST.get('id')
            content=request.POST.get('content')
            article=Article.objects.get(id=id)
            Comment.objects.create(
                article=article,
                content=content,
                user=user)

            # 修改文章评论数量
            article.comments_count += 1
            article.save()

            base_url = reverse('home:detail')

            path = "{}?id={}".format(base_url, article.id)

            return redirect(path)
        else:
            return redirect(reverse('user:login'))
